import axios from 'axios'

export default {
    namespaced: true,
    state: () => ({
        cart: []
    }),
    mutations:{
        getCartList(state, payload) {
            state.cart = payload
        },
        updataCartState(state, payload) {
            // payload: {id: 1, value: false}
            let index = state.cart.findIndex(item => item.id == payload.id)
            state.cart[index].goods_state = payload.value
        },
        updataCartCount(state, payload) {
            // payload: {id: 1, value: 2}
            let index = state.cart.findIndex(item => item.id == payload.id)
            state.cart[index].goods_count = payload.value
        },
        updateAllState(state, payload) {
            state.cart.forEach(item => item.goods_state = payload)
        }
    },
    actions:{
        async getCartList(context) {
            const res = await axios.get('https://www.escook.cn/api/cart')
            // console.log(res);
            context.commit('getCartList', res.data.list)
        }
    },
    getters:{
        allPrice(state) {
            return state.cart.filter(item => item.goods_state)
            .reduce((sum, item) => sum += item.goods_count * item.goods_price, 0)
        },
        allCount(state) {
            return state.cart.filter(item => item.goods_state)
            .reduce((sum, item) => sum += item.goods_count, 0)
        }
    }
}